package org.blame.rpc;

import com.rabbitmq.client.*;
import org.blame.constants.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeoutException;

public class Customer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL);

        Connection connection= connectionFactory.newConnection();

        //        2.开启信道
        Channel channel=connection.createChannel();


        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);
//        接收消息
//        最多只可以接收一个消息
        channel.basicQos(1);
        System.out.println("Awaiting RPC request");
        DefaultConsumer consumer=new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                AMQP.BasicProperties basicProperties=new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                System.out.println("消息已经成功的收到");

//                生成返回
                String message=new String(body);
                String response="request"+message+"response"+"处理成功";

                channel.basicPublish("", properties.getReplyTo(),basicProperties,response.getBytes(StandardCharsets.UTF_8));
//                手动对消息进行应答
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);
    }
}
